<template>
  <div class="action-container">
    <div class="action-buttons">
      <template v-for="button in sortedButtons" :key="button.name">
        <!-- 使用Element UI原生按钮 -->
        <el-button v-throttle-click="2000"
          v-if="button.visible !== false && button.useElButton === true"
          :type="button.type"
          :size="button.size || 'default'"
          @click="handleButtonClick(button.name, button.needConfirm)"
        >
          <!-- 显示Element Plus内置图标 -->
          <el-icon v-if="!button.customIcon && !button.imageUrl" :class="`icon-${button.name}`">
            <component :is="getIconComponent(button.icon)" />
          </el-icon>

          <!-- 显示自定义Element Plus图标 -->
          <el-icon
            v-else-if="button.customIcon && !button.imageUrl"
            :class="`icon-${button.name}`"
            :style="button.iconColor ? { color: button.iconColor } : {}"
          >
            <component :is="getIconComponent(button.customIcon)" />
          </el-icon>

          <!-- 显示自定义图片 -->
          <img
            v-else-if="button.imageUrl"
            :src="button.imageUrl"
            class="button-image"
            :alt="button.customLabel || button.label"
          />

          <!-- 显示按钮文字 -->
          <span>{{ button.customLabel || button.label }}</span>
        </el-button>
        
        <!-- 原有的自定义样式按钮 -->
        <el-button  v-throttle-click="button.throttleClick || 200"
          v-else-if="button.visible !== false"
          class="custom-action-btn"
          :class="`${button.name}-btn`"
          @click="handleButtonClick(button.name, button.needConfirm)"
        >
          <!-- 显示Element Plus内置图标 -->
          <el-icon
            v-if="!button.customIcon && !button.imageUrl"
            :class="`icon-${button.name}`"
          >
            <component :is="getIconComponent(button.icon)" />
          </el-icon>

          <!-- 显示自定义Element Plus图标 -->
          <el-icon
            v-else-if="button.customIcon && !button.imageUrl"
            :class="`icon-${button.name}`"
            :style="button.iconColor ? { color: button.iconColor } : {}"
          >
            <component :is="getIconComponent(button.customIcon)" />
          </el-icon>

          <!-- 显示自定义图片 -->
          <img
            v-else-if="button.imageUrl"
            :src="button.imageUrl"
            class="button-image"
            :alt="button.customLabel || button.label"
          />

          <!-- 显示按钮文字 -->
          <span>{{ button.customLabel || button.label }}</span>
        </el-button>
      </template>
    </div>

    <!-- 引入确认操作弹窗组件 -->
    <ConfirmDialog
      v-model:visible="confirmDialogVisible"
      :action="currentAction"
      :dialog-title="dialogTitle"
      @cancel="cancelConfirm"
      @confirm="confirmAction"
    />
  </div>
</template>

<script setup>
/**
 * @component ActionButtons
 * @description 通用操作按钮组件，支持预设按钮和自定义按钮，带权限控制和确认弹窗功能
 * @author WMS Team
 */
import { ref, computed } from "vue";
import { useTheme } from "@/hooks/useTheme";
import {
  CirclePlusFilled,
  CircleCheckFilled,
  RemoveFilled,
  CircleCloseFilled,
  UploadFilled,
  Upload,
  Document,
  Edit,
  Plus,
  Hide,
} from "@element-plus/icons-vue";
import ConfirmDialog from "./confirm-dialog.vue";
import { ElMessage } from "element-plus";

// 使用主题组合API获取当前主题按钮类型
const { themeType } = useTheme();

// 确认弹窗相关状态
const confirmDialogVisible = ref(false); // 控制确认弹窗显示状态
const currentAction = ref(""); // 当前操作类型（用于显示在确认弹窗中）
const currentButtonName = ref(""); // 当前操作的按钮名称
const dialogTitle = ref("提示"); // 确认弹窗标题

/**
 * 获取正确的图标组件
 * @param {string} iconName - 图标名称
 * @returns {Component} 图标组件
 */
const getIconComponent = (iconName) => {
  // 映射图标名称到导入的组件
  const iconMap = {
    CirclePlusFilled: CirclePlusFilled,
    CircleCheckFilled: CircleCheckFilled,
    RemoveFilled: RemoveFilled,
    CircleCloseFilled: CircleCloseFilled,
    UploadFilled: UploadFilled,
    Upload: Upload,
    Document: Document,
    Edit: Edit,
    Plus: Plus,
    Hide: Hide,
  };
  return iconMap[iconName] || iconName;
};

/**
 * 根据defaultImg获取默认图片
 * @param {string} defaultImg - 默认图片类型
 * @returns {string} 图片URL
 */
const getDefaultImage = (defaultImg) => {
  if (!defaultImg) return "";
  
  const imgMap = {
    // add: addImg.value,
    // enable: enableImg.value,
    // disable: disableImg.value,
    // delete: deleteImg.value,
    // import: importImg.value,
    // export: exportImg.value,
    // print: printImg.value,
    // zheng: zhengpingImg.value,
    // ci: cipingImg.value
  };
  
  return imgMap[defaultImg] || "";
};

/**
 * 显示确认对话框
 * @param {string} action - 操作类型描述
 * @param {string} buttonName - 按钮名称
 */
const showConfirmDialog = (action, buttonName) => {
  currentAction.value = action;
  currentButtonName.value = buttonName;

  // 获取按钮的确认弹窗标题
  const button = processedButtons.value.find((btn) => btn.name === buttonName);
  dialogTitle.value =
    button && button.confirmTitle ? button.confirmTitle : "提示";

  confirmDialogVisible.value = true;
};

/**
 * 取消确认操作
 */
const cancelConfirm = () => {
  confirmDialogVisible.value = false;
};

/**
 * 确认操作并触发对应事件
 */
const confirmAction = () => {
  confirmDialogVisible.value = false;

  // 触发对应的事件
  if (
    [
      "add",
      "export",
      "import",
      "enable",
      "disable",
      "delete",
      "viewLog",
      "edit",
      "hide",
      "zheng",
      "ci",
    ].includes(currentButtonName.value)
  ) {
    emit(currentButtonName.value);
  } else {
    emit("button-click", currentButtonName.value);
  }
};

/**
 * 处理按钮点击事件
 * @param {string} buttonName - 按钮名称
 * @param {boolean} needConfirm - 是否需要确认
 */
const handleButtonClick = (buttonName, needConfirm) => {
  // 获取按钮配置
  const buttonConfig = processedButtons.value.find(btn => btn.name === buttonName);
  
  // 检查此按钮是否在不需要确认的按钮列表中
  if (props.noConfirmButtons.includes(buttonName) || (buttonConfig && buttonConfig.noConfirm === true)) {
    // 尝试调用指定事件，如果不是标准事件，则通过button-click事件传递
    if (
      [
        "add",
        "export",
        "import",
        "enable",
        "disable",
        "delete",
        "viewLog",
        "edit",
        "hide",
        "zheng",
        "ci",
      ].includes(buttonName)
    ) {
      emit(buttonName);
    } else {
      emit("button-click", buttonName);
    }
    return;
  }

  // 如果是需要选择数据的按钮，且没有选择数据
  if (
    (props.needSelectButtons.includes(buttonName) || (buttonConfig && buttonConfig.needSelect === true)) &&
    props.selectedData &&
    props.selectedData.length === 0
  ) {
    ElMessage.warning("请先选择数据");
    return;
  }

  // 使用自定义确认对话框
  if (needConfirm) {
    let actionText = "";
    switch (buttonName) {
      case "enable":
        actionText = "启用";
        break;
      case "disable":
        actionText = "停用";
        break;
      case "delete":
        actionText = "删除";
        break;
      default:
        // 对于自定义按钮，使用其标签作为操作文本
        const button = processedButtons.value.find(
          (btn) => btn.name === buttonName
        );
        actionText = button ? button.customLabel || button.label : buttonName;
    }
    showConfirmDialog(actionText, buttonName);
  } else {
    // 对于不需要确认的按钮，直接触发对应的事件
    if (
      [
        "add",
        "export",
        "import",
        "enable",
        "disable",
        "delete",
        "viewLog",
        "edit",
        "hide",
        "zheng",
        "ci",
      ].includes(buttonName)
    ) {
      emit(buttonName);
    } else {
      emit("button-click", buttonName);
    }
  }
};

// 扩展emits，支持自定义事件
const emit = defineEmits({
  add: null, // 新增
  export: null, // 导出
  import: null, // 导入
  enable: null, // 启用
  disable: null, // 停用
  delete: null, // 删除
  viewLog: null, // 查看日志
  edit: null, // 编辑
  hide: null, // 隐藏0库存商品
  zheng: null, // 正品转次
  ci: null, // 次品转正
  // 添加自定义按钮事件处理器，支持任意事件名
  "button-click": (buttonName) => {
    return typeof buttonName === "string";
  },
});

/**
 * 组件属性定义
 */
const props = defineProps({
  /**
   * 按钮配置对象，包含所有按钮的配置信息
   * @example { add: { visible: true, order: 1, type: 'success', noConfirm: true, needSelect: false }, custom: { name: 'custom', label: '自定义', icon: 'Edit', needConfirm: true } }
   */
  buttons: {
    type: Object,
    default: () => ({
      add: { visible: true, order: 1, type: "success" },
      enable: { visible: true, order: 2 },
      disable: { visible: true, order: 3 },
      delete: { visible: false, order: 4, type: "danger" },
      import: { visible: false, order: 5 },
      export: { visible: false, order: 6 },
      viewLog: { visible: false, order: 7 },
      edit: { visible: false, order: 8 },
      hide: { visible: false, order: 9 },
      zheng: { visible: false, order: 10 },
      ci: { visible: false, order: 11 },
    }),
  },
  /**
   * 已选择的数据，用于判断需要选择数据的按钮是否可用
   */
  selectedData: {
    type: Array,
    default: () => [],
  },
  /**
   * 不需要确认弹窗的按钮列表
   * @example ['add', 'export']
   * @deprecated 推荐在 buttons 对象中设置 noConfirm: true，此属性仅为向后兼容保留
   */
  noConfirmButtons: {
    type: Array,
    default: () => [],
  },
  /**
   * 需要选择数据的按钮列表
   * 这些按钮在未选择数据时会显示警告
   * @example ['enable', 'disable', 'delete']
   * @deprecated 推荐在 buttons 对象中设置 needSelect: true，此属性仅为向后兼容保留
   */
  needSelectButtons: {
    type: Array,
    default: () => ["enable", "disable", "delete"],
  },
  /**
   * 操作权限控制对象（兼容旧版API）
   * @example { add: true, delete: false }
   */
  actionPermissions: {
    type: Object,
    default: null,
  },
  /**
   * 按钮排序对象（兼容旧版API）
   * @example { add: 1, delete: 2 }
   * @deprecated 推荐在 buttons 对象中设置 order 属性，此属性仅为向后兼容保留
   */
  buttonOrder: {
    type: Object,
    default: null,
  },
  // 以下是兼容旧版API的按钮类型属性
  addType: {
    type: String,
    default: null,
  },
  exportType: {
    type: String,
    default: null,
  },
  importType: {
    type: String,
    default: null,
  },
  enableType: {
    type: String,
    default: null,
  },
  disableType: {
    type: String,
    default: null,
  },
  viewLogType: {
    type: String,
    default: null,
  },
  deleteType: {
    type: String,
    default: null,
  },
  editType: {
    type: String,
    default: null,
  },
});

// 正品转次图片
// const zhengpingImg = ref(
//   new URL("@/assets/images/zhengping.png", import.meta.url).href
// );
// // 次品转正图片
// const cipingImg = ref(
//   new URL("@/assets/images/ciping.png", import.meta.url).href
// );
// // 新增图片
// const addImg = ref(
//   new URL("@/assets/images/button/add.png", import.meta.url).href
// );
// // 启用图片
// const enableImg = ref(
//   new URL("@/assets/images/button/enable.png", import.meta.url).href
// );
// // 停用图片
// const disableImg = ref(
//   new URL("@/assets/images/button/disable.png", import.meta.url).href
// );
// // 删除图片
// const deleteImg = ref(
//   new URL("@/assets/images/button/delete.png", import.meta.url).href
// );
// // 导出图片
// const exportImg = ref(
//   new URL("@/assets/images/button/export.png", import.meta.url).href
// );
// // 导入图片
// const importImg = ref(
//   new URL("@/assets/images/button/import.png", import.meta.url).href
// );
// // 打印图片
// const printImg = ref(
//   new URL("@/assets/images/button/print.png", import.meta.url).href
// );
/**
 * 默认按钮基础配置
 * 定义了每个内置按钮的基本属性
 */
const defaultButtons = [
  {
    name: "add",
    label: "新增",
    icon: "CirclePlusFilled",
    // imageUrl: addImg.value,
    needConfirm: false,
    confirmTitle: "提示",
    needSelect: false,
    useElButton: false,
  },
  {
    name: "enable",
    label: "启用",
    icon: "CircleCheckFilled",
    // imageUrl: enableImg.value,
    needConfirm: true,
    confirmTitle: "提示",
    needSelect: true,
    useElButton: false
  },
  {
    name: "disable",
    label: "停用",
    icon: "RemoveFilled",
    // imageUrl: disableImg.value,
    needConfirm: true,
    confirmTitle: "提示",
    needSelect: true,
    useElButton: false
  },
  {
    name: "delete",
    label: "删除",
    icon: "CircleCloseFilled",
    // imageUrl: deleteImg.value,
    needConfirm: true,
    confirmTitle: "提示",
    needSelect: true,
    useElButton: false
  },
  {
    name: "import",
    label: "导入",
    icon: "UploadFilled",
    // imageUrl: importImg.value,
    needConfirm: false,
    confirmTitle: "提示",
    needSelect: false,
    useElButton: false
  },
  {
    name: "export",
    label: "导出",
    icon: "Upload",
    // imageUrl: exportImg.value,
    needConfirm: false,
    confirmTitle: "提示",
    needSelect: false,
    useElButton: false,
    throttleClick: 3000
  },
  {
    name: "viewLog",
    label: "日志",
    icon: "Document",
    needConfirm: false,
    confirmTitle: "提示",
    needSelect: false,
    useElButton: false
  },
  {
    name: "edit",
    label: "编辑",
    icon: "Edit",
    needConfirm: false,
    confirmTitle: "提示",
    needSelect: false,
    useElButton: false
  },
  {
    name: "hide",
    label: "隐藏0库存商品",
    icon: "Hide",
    needConfirm: false,
    confirmTitle: "提示",
    needSelect: false,
    useElButton: false
  },
  {
    name: "zheng",
    label: "正品转次",
    icon: "Hide",
    // imageUrl: zhengpingImg.value,
    needConfirm: false,
    confirmTitle: "提示",
    needSelect: false,
    useElButton: false
  },
  {
    name: "ci",
    label: "次品转正",
    icon: "Hide",
    // imageUrl: cipingImg.value,
    needConfirm: false,
    confirmTitle: "提示",
    needSelect: false,
    useElButton: false
  }
  
];

/**
 * 处理后的按钮配置
 * 合并默认配置、buttons配置和兼容旧版API的配置
 */
const processedButtons = computed(() => {
  // 从默认按钮开始
  let buttonsList = [...defaultButtons].map((btn) => ({ ...btn }));

  // 首先根据actionPermissions设置按钮可见性
  if (props.actionPermissions) {
    // 处理标准按钮
    buttonsList.forEach((button) => {
      // 如果actionPermissions中定义了该按钮
      if (props.actionPermissions[button.name] !== undefined) {
        button.visible = !!props.actionPermissions[button.name];
      } else {
        button.visible = false; // 未定义则不可见
      }
    });
  }

  // 如果有buttons配置，处理按钮的其他属性（但不覆盖actionPermissions设置的可见性）
  if (props.buttons && Object.keys(props.buttons).length > 0) {
    buttonsList.forEach((button) => {
      if (props.buttons[button.name]) {
        const buttonConfig = props.buttons[button.name];

        // 复制除visible以外的所有属性
        const { visible, ...otherProps } = buttonConfig;
        Object.assign(button, otherProps);

        // 只有在没有actionPermissions时，才使用buttons中的visible属性
        if (!props.actionPermissions) {
          button.visible = visible !== false;
        }
      } else if (!props.actionPermissions) {
        // 如果buttons中没有该按钮且没有actionPermissions，设为不可见
        button.visible = false;
      }
    });
    
    // 处理buttons中的自定义按钮（处理不属于默认按钮的对象）
    Object.entries(props.buttons).forEach(([key, buttonConfig]) => {
      // 检查是否是标准按钮
      const isStandardButton = buttonsList.some(btn => btn.name === key);
      
      // 如果不是标准按钮且包含name属性，则视为自定义按钮
      if (!isStandardButton && buttonConfig.name) {
        // 处理defaultImg，获取对应的图片URL
        let imageUrl = buttonConfig.imageUrl || "";
        if (buttonConfig.defaultImg && !imageUrl) {
          imageUrl = getDefaultImage(buttonConfig.defaultImg);
        }
        
        // 设置默认属性
        const customButton = {
          name: buttonConfig.name || key,
          label: buttonConfig.label || `${buttonConfig.name || key}`,
          icon: buttonConfig.icon || "",
          customIcon: buttonConfig.customIcon || "",
          imageUrl: imageUrl,
          needConfirm: buttonConfig.needConfirm !== undefined ? buttonConfig.needConfirm : false,
          confirmTitle: buttonConfig.confirmTitle || "提示",
          type: buttonConfig.type || themeType.value || "", // 使用传入的type或默认主题类型
          visible: buttonConfig.visible !== false,
          order: buttonConfig.order !== undefined ? buttonConfig.order : 100,
          customLabel: buttonConfig.customLabel || "",
          iconColor: buttonConfig.iconColor || "", // 添加图标颜色支持
          ...buttonConfig, // 保留其他可能的自定义属性
        };
        
        // 将自定义按钮添加到按钮列表
        buttonsList.push(customButton);
      }
      // 如果不是标准按钮且key作为name也能作为一个有效的按钮（向后兼容简化的按钮定义）
      else if (!isStandardButton) {
        // 处理defaultImg，获取对应的图片URL
        let imageUrl = buttonConfig.imageUrl || "";
        if (buttonConfig.defaultImg && !imageUrl) {
          imageUrl = getDefaultImage(buttonConfig.defaultImg);
        }
        
        const customButton = {
          name: key,
          label: buttonConfig.label || key,
          icon: buttonConfig.icon || "",
          customIcon: buttonConfig.customIcon || "",
          imageUrl: imageUrl,
          needConfirm: buttonConfig.needConfirm !== undefined ? buttonConfig.needConfirm : false,
          confirmTitle: buttonConfig.confirmTitle || "提示",
          type: buttonConfig.type || themeType.value || "",
          visible: buttonConfig.visible !== false,
          order: buttonConfig.order !== undefined ? buttonConfig.order : 100,
          customLabel: buttonConfig.customLabel || "",
          iconColor: buttonConfig.iconColor || "",
          ...buttonConfig,
        };
        
        buttonsList.push(customButton);
      }
    });
  } else if (!props.actionPermissions) {
    // 既没有buttons也没有actionPermissions，使用默认配置
    buttonsList.forEach((button) => {
      if (["add", "enable", "disable"].includes(button.name)) {
        button.visible = true;
      } else {
        button.visible = false;
      }
    });
  }

  // 兼容旧API - 权限
  if (props.actionPermissions) {
    Object.entries(props.actionPermissions).forEach(([name, value]) => {
      const buttonIndex = buttonsList.findIndex((b) => b.name === name);
      if (buttonIndex !== -1) {
        buttonsList[buttonIndex].visible = value;
      }
    });
  }

  // 兼容旧API - 排序
  if (props.buttonOrder) {
    Object.entries(props.buttonOrder).forEach(([name, order]) => {
      const buttonIndex = buttonsList.findIndex((b) => b.name === name);
      if (buttonIndex !== -1) {
        buttonsList[buttonIndex].order = order;
      }
    });
  }

  // 兼容旧API - 按钮类型
  if (props.addType !== null) {
    const addButton = buttonsList.find((b) => b.name === "add");
    if (addButton) addButton.type = props.addType;
  }
  if (props.exportType !== null) {
    const exportButton = buttonsList.find((b) => b.name === "export");
    if (exportButton) exportButton.type = props.exportType;
  }
  if (props.importType !== null) {
    const importButton = buttonsList.find((b) => b.name === "import");
    if (importButton) importButton.type = props.importType;
  }
  if (props.enableType !== null) {
    const enableButton = buttonsList.find((b) => b.name === "enable");
    if (enableButton) enableButton.type = props.enableType;
  }
  if (props.disableType !== null) {
    const disableButton = buttonsList.find((b) => b.name === "disable");
    if (disableButton) disableButton.type = props.disableType;
  }
  if (props.viewLogType !== null) {
    const viewLogButton = buttonsList.find((b) => b.name === "viewLog");
    if (viewLogButton) viewLogButton.type = props.viewLogType;
  }
  if (props.deleteType !== null) {
    const deleteButton = buttonsList.find((b) => b.name === "delete");
    if (deleteButton) deleteButton.type = props.deleteType;
  }
  if (props.editType !== null) {
    const editButton = buttonsList.find((b) => b.name === "edit");
    if (editButton) editButton.type = props.editType;
  }

  return buttonsList;
});

/**
 * 排序后的按钮列表
 * 按order属性升序排列
 */
const sortedButtons = computed(() => {
  return [...processedButtons.value].sort(
    (a, b) => (a.order || 99) - (b.order || 99)
  );
});
</script>

<style lang="scss" scoped>
.action-container {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;

  .action-buttons {
    display: flex;
    gap: 10px;
  }

  // 使用新的样式文件定义的全局样式变量，保留此注释
  .custom-action-btn {
    // 所有自定义样式已移至全局样式文件：/src/styles/components/action-buttons.scss，保留此注释
    // 仅添加宽度自适应相关样式
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 80px;
    padding: 0 15px;
    box-sizing: border-box;
    white-space: nowrap;
    width: auto;
  }

  .button-image {
    width: 16px;
    height: 16px;
    object-fit: contain;
    margin-right: 4px;
    vertical-align: middle;
  }
}
</style>
